Page({
    data: {
    // 轮播图数据
    banners: [
      {
        id: 1,
        image: 'https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?w=800&h=400&fit=crop'
      },
      {
        id: 2, 
        image: 'https://images.unsplash.com/photo-1552519507-da3b142c6e3d?w=800&h=400&fit=crop'
      },
      {
        id: 3,
        image: 'https://images.unsplash.com/photo-1503376780353-7e6692767b70?w=800&h=400&fit=crop'
      }
    ],

    // 品牌数据
      brands: [
      { 
        id: 1, 
        name: '特斯拉', 
        value: 'tesla',
        logo: 'https://logos-world.net/wp-content/uploads/2021/03/Tesla-Logo.png',
        bgColor: '#E53E3E'
      },
      { 
        id: 2, 
        name: '蔚来', 
        value: 'nio',
        logo: 'https://www.carlogos.org/logo/NIO-logo-2014-2048x2048.png',
        bgColor: '#38B2AC'
      },
      { 
        id: 3, 
        name: '小鹏', 
        value: 'xpeng',
        logo: 'https://www.carlogos.org/logo/XPeng-logo-2048x2048.png',
        bgColor: '#2D3748'
      },
      { 
        id: 4, 
        name: '比亚迪', 
        value: 'byd',
        logo: 'https://www.carlogos.org/logo/BYD-logo-2007-2048x2048.png',
        bgColor: '#E53E3E'
      },
      { 
        id: 5, 
        name: '理想', 
        value: 'lixiang',
        logo: 'https://www.carlogos.org/logo/Li-Auto-logo-2048x2048.png',
        bgColor: '#4A5568'
      }
    ],

    // 服务特色
    features: ['100%自营', '专业质检', '货到付款', '7天无理由退车'],

    // 脱销公告
      announcement: '九月优惠上新啦~',

    // 车辆数据
    cars: [],

    // 分页参数
    page: 1,
    pageSize: 6,
    hasMore: true,
    loading: false,
    refresherTriggered: false,
      // // 底部导航数据
    // navItems: [
    //   {
    //     id: 1,
    //     name: '发现',
    //     icon: 'https://img.icons8.com/ios/50/000000/home.png',
    //     active: true
    //   },
    //   {
    //     id: 2,
    //     name: '买车',
    //     icon: 'https://img.icons8.com/ios/50/000000/car.png',
    //     active: false
    //   },
    //   {
    //     id: 3,
    //     name: '卖车',
    //     icon: 'https://img.icons8.com/ios/50/000000/sell.png',
    //     active: false
    //   },
    //   {
    //     id: 4,
    //     name: '我的',
    //     icon: 'https://img.icons8.com/ios/50/000000/user.png',
    //     active: false
    //   }
    // ],

    // 模拟车辆数据库
    carDatabase: [
    {
      id: 1,
      name: '特斯拉 Model 3',
      subtitle: '2022款后轮驱动版',
      year: '2016年',
      mileage: '2.27万公里',
      location: 'EAP',
      price: '37.56万',
      downPayment: '7.15万',
      image: 'https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?w=400&h=300&fit=crop',
      isHot: true,
      isSelected: false
    },
    {
      id: 2,
      name: '特斯拉 Model 3', 
      subtitle: '2022款后轮驱动版',
      year: '2016年',
      mileage: '2.27万公里',
      location: 'EAP',
      price: '37.56万',
      downPayment: '7.15万',
      image: 'https://images.unsplash.com/photo-1552519507-da3b142c6e3d?w=400&h=300&fit=crop',
      isHot: false,
      isSelected: true
    },
    {
      id: 3,
      name: '特斯拉 Model Y',
      subtitle: '2022款长续航版',
      year: '2017年',
      mileage: '1.85万公里',
      location: 'EAP',
      price: '42.88万',
      downPayment: '8.58万',
      image: 'https://images.unsplash.com/photo-1503376780353-7e6692767b70?w=400&h=300&fit=crop',
      isHot: false,
      isSelected: true
    },
    {
      id: 4,
      name: '蔚来 ES6',
      subtitle: '2021款运动版',
      year: '2020年',
      mileage: '3.12万公里', 
      location: 'EAP',
      price: '28.66万',
      downPayment: '5.73万',
      image: 'https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?w=400&h=300&fit=crop',
      isHot: false,
      isSelected: true
    },
    {
      id: 5,
      name: '小鹏 P7',
      subtitle: '2023款智享版',
      year: '2022年',
      mileage: '0.8万公里',
      location: 'EAP',
      price: '22.99万',
      downPayment: '4.60万',
      image: 'https://images.unsplash.com/photo-1552519507-da3b142c6e3d?w=400&h=300&fit=crop',
      isHot: true,
      isSelected: false
    },
    {
      id: 6,
      name: '比亚迪 汉EV',
      subtitle: '2023款创世版',
      year: '2022年',
      mileage: '1.2万公里',
      location: 'EAP',
      price: '25.58万',
      downPayment: '5.12万',
      image: 'https://images.unsplash.com/photo-1503376780353-7e6692767b70?w=400&h=300&fit=crop',
      isHot: false,
      isSelected: true
    },
    {
      id: 7,
      name: '理想 ONE',
      subtitle: '2022款增程版',
      year: '2021年',
      mileage: '2.5万公里',
      location: 'EAP',
      price: '28.88万',
      downPayment: '5.78万',
      image: 'https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?w=400&h=300&fit=crop',
      isHot: false,
      isSelected: true
    },
    {
      id: 8,
      name: '蔚来 ET7',
      subtitle: '2023款首发版',
      year: '2022年',
      mileage: '0.5万公里',
      location: 'EAP',
      price: '42.80万',
      downPayment: '8.56万',
      image: 'https://images.unsplash.com/photo-1552519507-da3b142c6e3d?w=400&h=300&fit=crop',
      isHot: true,
      isSelected: false
    },
    {
      id: 9,
      name: '小鹏 G9',
      subtitle: '2023款Max版',
      year: '2022年',
      mileage: '1.1万公里',
      location: 'EAP',
      price: '35.99万',
      downPayment: '7.20万',
      image: 'https://images.unsplash.com/photo-1503376780353-7e6692767b70?w=400&h=300&fit=crop',
      isHot: false,
      isSelected: true
    },
    {
      id: 10,
      name: '特斯拉 Model S',
      subtitle: '2022款Plaid版',
      year: '2021年',
      mileage: '1.8万公里',
      location: 'EAP',
      price: '89.99万',
      downPayment: '18.00万',
      image: 'https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?w=400&h=300&fit=crop',
      isHot: true,
      isSelected: false
    },
    {
      id: 11,
      name: '比亚迪 唐EV',
      subtitle: '2023款尊贵版',
      year: '2022年',
      mileage: '0.9万公里',
      location: 'EAP',
      price: '32.98万',
      downPayment: '6.60万',
      image: 'https://images.unsplash.com/photo-1552519507-da3b142c6e3d?w=400&h=300&fit=crop',
      isHot: false,
      isSelected: true
    },
    {
      id: 12,
      name: '理想 L9',
      subtitle: '2023款Max版',
      year: '2022年',
      mileage: '0.6万公里',
      location: 'EAP',
      price: '45.98万',
      downPayment: '9.20万',
      image: 'https://images.unsplash.com/photo-1503376780353-7e6692767b70?w=400&h=300&fit=crop',
      isHot: false,
      isSelected: true
    }
    ]
  },

  // 页面生命周期
  onLoad: function (options) {
    console.log('页面加载完成');
    this.loadBrandData();
    this.loadCarData();
  },

  onShow: function () {
    // 页面显示时刷新数据
    console.log('页面显示');
  },

  // 下拉刷新
  onPullDownRefresh: function () {
    // 兼容：若仍被触发，直接转向 scroll-view 刷新逻辑
    this.onRefresherRefresh();
  },

  // 上拉加载更多
  onReachBottom: function () {
    // 兼容：页面底部触达时也复用 scroll-view 触底逻辑
    this.onScrollToLower();
  },

  // 加载品牌数据
  loadBrandData: function () {
    console.log('开始加载品牌数据...');
    
    wx.request({
      url: 'http://localhost:6001/carBrand/findAll',
      method: 'GET',
      success: (res) => {
        console.log('品牌数据加载成功:', res.data);
        if (res.data && Array.isArray(res.data) && res.data.length > 0) {
          // 使用API返回的品牌数据，保持原有的显示格式
          const formattedBrands = res.data.map(brand => ({
            id: brand.id,
            brandName: brand.brandName,
            brandLogo: brand.brandLogo || 'https://img.icons8.com/ios/50/000000/car.png', // 默认图标
            // 保持兼容性
            name: brand.brandName,
            value: brand.brandName.toLowerCase().replace(/\s+/g, ''),
            logo: brand.brandLogo || 'https://img.icons8.com/ios/50/000000/car.png'
          }));
          
          this.setData({
            brands: formattedBrands
          });
          
          console.log('品牌数据格式化完成:', formattedBrands);
        } else {
          console.warn('API返回的品牌数据为空，使用静态数据');
        }
      },
      fail: (err) => {
        console.error('品牌数据加载失败:', err);
        wx.showToast({
          title: '品牌数据加载失败，使用默认数据',
          icon: 'none'
        });
        // 保持原有的静态数据作为备用
        console.log('使用静态品牌数据作为备用');
      }
    });
  },

  // 加载车辆数据
  loadCarData: function () {
    console.log('开始加载车辆数据...');
    
    const { page, pageSize, carDatabase } = this.data;
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const newCars = carDatabase.slice(startIndex, endIndex);
    
    console.log(`加载第${page}页，共${newCars.length}辆车`);
    
    this.setData({
      cars: newCars,
      hasMore: endIndex < carDatabase.length
    });
  },


  // 加载更多车辆
  loadMoreCars: function () {
    console.log('开始加载更多车辆');
    
    this.setData({
      loading: true
    });

    setTimeout(() => {
      const { page, pageSize, cars, carDatabase } = this.data;
      const nextPage = page + 1;
      const startIndex = (nextPage - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      const newCars = carDatabase.slice(startIndex, endIndex);
      
      if (newCars.length > 0) {
        this.setData({
          cars: cars.concat(newCars),
          page: nextPage,
          loading: false,
          hasMore: endIndex < carDatabase.length
        });
        
        wx.showToast({
          title: `加载了${newCars.length}辆车`,
          icon: 'success'
        });
      } else {
        this.setData({
          loading: false,
          hasMore: false
        });
        
        wx.showToast({
          title: '没有更多车辆了',
          icon: 'none'
        });
      }
    }, 500);
  },

  // scroll-view 下拉刷新事件
  onRefresherRefresh: function () {
    if (this.data.refresherTriggered) return;
    this.setData({ refresherTriggered: true, page: 1, cars: [], hasMore: true, loading: false });
    setTimeout(() => {
      this.loadCarData();
      this.setData({ refresherTriggered: false });
      wx.showToast({ title: '刷新成功', icon: 'success' });
    }, 400);
  },

  // scroll-view 触底事件
  onScrollToLower: function () {
    if (this.data.loading || !this.data.hasMore) return;
    this.loadMoreCars();
  },

  // 选择品牌
  selectBrand: function(e) {
    const brand = e.currentTarget.dataset.brand;
    console.log('选择品牌：', brand);
    
    // 处理品牌数据格式 - 支持API数据和静态数据
    let brandInfo = {};
    
    if (brand.brandName) {
      // 来自API的品牌数据
      brandInfo = {
        id: brand.id,
        value: brand.brandName.toLowerCase().replace(/\s+/g, ''),
        name: brand.brandName,
        logo: brand.brandLogo
      };
    } else {
      // 静态品牌数据
      brandInfo = {
        value: brand.value,
        name: brand.name,
        logo: brand.logo
      };
    }
    
    console.log('处理后的品牌信息：', brandInfo);
    
    // 将品牌信息存储到全局数据中
    getApp().globalData = getApp().globalData || {};
    getApp().globalData.selectedBrand = brandInfo;
    
    // 显示跳转提示
    wx.showToast({
      title: `正在跳转到${brandInfo.name}`,
      icon: 'loading',
      duration: 800
    });
    
    // 跳转到买车页面
    wx.switchTab({
      url: '/pages/buy-car/buy-car'
    });
  },

  // 显示更多品牌
  showMoreBrands: function() {
    console.log('显示更多品牌');
    wx.showToast({
      title: '更多品牌',
      icon: 'none'
    });
  },

  // 查看车辆详情
  viewCarDetail: function(e) {
    const car = e.currentTarget.dataset.car;
    console.log('查看车辆详情：', car);
    
    // 跳转到商品详情页面
    wx.navigateTo({
      url: `/pages/car-detail/car-detail?id=${car.id}`
    });
  },

  // 切换底部导航
  switchTab: function(e) {
    const index = e.currentTarget.dataset.index;
    const navItems = this.data.navItems;
    
    // 根据不同的导航项进行跳转
    switch(index) {
      case 0: // 发现
        // 当前页面，不需要跳转
        break;
      case 1: // 买车
        wx.navigateTo({
          url: '/pages/buy-car/buy-car'
        });
        return;
      case 2: // 卖车
        wx.showToast({
          title: '卖车功能开发中',
          icon: 'none'
        });
        return;
      case 3: // 我的
        wx.showToast({
          title: '我的功能开发中',
          icon: 'none'
        });
        return;
    }
    
    // 更新导航状态（只有在当前页面时才更新）
    navItems.forEach((item, i) => {
      item.active = i === index;
    });
    
    this.setData({
      navItems: navItems
    });
  },

  // 手动测试功能
  testRefresh: function() {
    this.onPullDownRefresh();
  },

  testLoadMore: function() {
    this.onReachBottom();
  }
  });
